package com.dtflys.easyel.runtime.eval;

import com.dtflys.easyel.ast.ASTAccessExpression;
import com.dtflys.easyel.ast.ASTType;
import com.dtflys.easyel.exception.EasyElAccessException;
import com.dtflys.easyel.exception.EasyElEvalException;
import com.dtflys.easyel.exception.EasyElNullException;
import com.dtflys.easyel.runtime.EasyElRuntimeContext;
import com.dtflys.easyel.utils.AccessUtils;

import java.lang.reflect.InvocationTargetException;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class AccessEvaluator {

    public Object evaluate(EasyElRuntimeContext context, ASTAccessExpression accessExpression, Object left) {
        if (left == null) {
            throw new EasyElNullException(context, accessExpression);
        }
        String accessName = accessExpression.getAccessName().getText();
        try {
            if (accessExpression.isStatic()) {
                return AccessUtils.accessStaticField((ASTType) left, accessName);
            } else {
                return AccessUtils.accessObject(left, accessName);
            }
        } catch (IllegalAccessException e) {
            throw new EasyElEvalException(context, accessExpression, e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new EasyElEvalException(context, accessExpression, e.getMessage(), e);
        } catch (EasyElAccessException e) {
            throw new EasyElEvalException(context, accessExpression, e.getMessage());
        }
    }
}
